package hu.plajko;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.bson.types.ObjectId;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Reference;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoTest {

	@Entity
	public static class Data2 {
		@Id
		ObjectId id;

		@Indexed
		String text;

		public Data2() {
		}

		public Data2(String text) {
			super();
			this.text = text;
		}

		@Override
		public String toString() {
			return "Data2 [id=" + id + ", text=" + text + "]";
		}
	}

	@Entity
	public static class Data {
		@Id
		ObjectId id;

		String text;

		@Reference
		@Indexed
		List<Data2> children = new ArrayList<Data2>();

		public List<Data2> getChildren() {
			return children;
		}

		public void setChildren(List<Data2> children) {
			this.children = children;
		}

		public Data() {
		}

		@Override
		public String toString() {
			return "Data [id=" + id + ", text=" + text + ", children=" + children + "]";
		}

		public Data(String text) {
			super();
			this.text = text;
		}

	}

	public static void main(String[] args) throws UnknownHostException, MongoException {

		Mongo mongo = new Mongo("localhost",12345);
		Morphia morphia = new Morphia();
		morphia.map(Data.class);
		Datastore ds = morphia.createDatastore(mongo, "alma");

		for (int i = 0; i < 0; i++) {
			Data d = new Data("asdasdasd" + new Random().nextInt());
			for (int j = 0; j < 1000; j++) {
				d.getChildren().add(new Data2("alma" + new Random().nextInt()));
			}
			ds.save(d.getChildren());
			ds.save(d);
		}

		// ds.getCollection(Data.class).drop();
		// ds.getCollection(Data2.class).drop();

		//ds.ensureIndexes();
		
		System.out.println(ds.getCollection(Data2.class).count());
		System.out.println(ds.find(Data.class).countAll());

		//System.out.println(ds.find(Data.class).get());
		System.out.println(ds.find(Data2.class).field("text").contains("987654").countAll());
		System.out.println(ds.find(Data.class).field("children").hasAnyOf(//
				ds.find(Data2.class).field("text").contains("987654").fetchKeys()).countAll());
		
		
	}

}
